//
//  SpecialWebViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/30.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import WebKit

class SpecialWebViewController: KMViewController {

    ///webview
    fileprivate var webView : WKWebView!
    
    fileprivate var isPush = true
    
    ///链接
    fileprivate var urlStr  = ""
    
    ///进度条
    fileprivate let progressView = UIProgressView()
    
    //需要移除的标签
    var removeElements = ["header","app-download","crumbs","footer"]
    
    let config = WKWebViewConfiguration()
    
    init(urlString:String?,title:String? = "") {
        super.init(nibName: nil, bundle: nil)
        
        self.urlStr = urlString ?? ""
        self.title = title
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.isPush = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        progressView.trackTintColor = UIColor.clear
        progressView.progressTintColor = UIColor.moveColor()
        self.view.addSubview(progressView)
        
        progressView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 5))
        }
        
        createWebView()
        
        self.view.bringSubview(toFront: progressView)
        
        //隐藏返回图标
        self.navigationController?.navigationBar.backIndicatorImage = UIImage()
        
        //自定义返回图标
        let backButton = UIButton.init(frame: .init(x: 0, y: (StatusBarAddNavBarHeight-StatusBarHeight-30)/2, width: 30, height: 30))
        backButton.setImage(#imageLiteral(resourceName: "back_arrow"), for: .normal)
        backButton.addTarget(self, action: #selector(goBackAction), for: .touchUpInside)
        self.navigationController?.navigationBar.addSubview(backButton)
        
    }
    
    
    //MARK: 页面回退
    @objc fileprivate func goBackAction() {
        
        if self.webView.canGoBack {
            self.webView.goBack()
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webView.removeObserver(self, forKeyPath: "title")
    }
    
    fileprivate func createWebView() {

        //交互设置
        config.preferences = WKPreferences()
        config.preferences.minimumFontSize = 10
        config.preferences.javaScriptEnabled = true
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        config.userContentController = WKUserContentController()
        config.processPool = WKProcessPool()
        
        self.webView = WKWebView.init(frame: .zero, configuration: config)
        //路径编码
        let string = self.urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let url = URL.init(string: string ?? "") {
            let request = URLRequest.init(url: url)
            webView.load(request)
        }
        webView.navigationDelegate = self
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        
        
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if "estimatedProgress" == keyPath {
            self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.progressView.progress == 0 {
                self.progressView.isHidden = false
            }else if self.progressView.progress == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    if self.progressView.progress == 1 {
                        self.progressView.progress = 0
                        self.progressView.isHidden = true
                    }
                }
            }
        }else if "title" == keyPath {
            self.title = webView.title
        }
        
        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension SpecialWebViewController : WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler {
    
    //MARK: 实现js注入方法的协议方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if message.name == "collectSendKey" {
            
                //通过id获取链接
                KMTool.requestMethod(.get, URLString: url_getHref, parameters: ["psw":"kameng98_loan","id":message.body], success: { (value, json) in
                    
                    if let dic = json.dictionaryObject {
                        
                        var string = ""
                        
                        let app_apply_access = dic["app_apply_access"] as? String
                        let m_apply_access = dic["m_apply_access"] as? String
                        let apply_access = dic["apply_access"] as? String
                        
                        if app_apply_access != nil && app_apply_access != "" {
                            string = app_apply_access!
                        }else if m_apply_access != nil && m_apply_access != "" {
                                string = m_apply_access!
                        }else if apply_access != nil && apply_access != "" {
                        
                            string = apply_access!
                        
                        }
                        
                        if string == "" {
                            return
                        }
                        
                        //生成记录
                        KMTool.generateRecords(idString: "\(message.body)")
                        let WebDetailsVc = WebDetailsViewController.init(urlString: string)
                    self.navigationController?.pushViewController(WebDetailsVc, animated: true)
                        
                    }else{
                        KMTool.showText(_text: global_requestFailed)
                    }
                    
                }) {
                    
                }
            
        }
        
    }
    
    //MARK: 页面加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        KMTool.showText(_text: global_requestFailed)
    }
    
    
    
    //MARK: 页面加载成功
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        KMTool.showText(_text: global_loadSuccess)
        
        //重写js方法
        let js = "function credit_record(id, series = 0){" +
        "window.webkit.messageHandlers.collectSendKey.postMessage(id);" + "}"
        self.webView.evaluateJavaScript(js, completionHandler: nil)
        config.userContentController.add(self, name: "collectSendKey")
        
    }
    
    //MARK: 监听js的alert弹出框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        completionHandler()
    }
    
    
    //MARK: 拦截网页点击事件
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        let urlString = navigationResponse.response.url?.absoluteString
        
        if urlString! == self.urlStr {
            decisionHandler(.allow)
            return
        }
        
        if !(urlString!.contains("kameng98.com")) && !(urlString!.contains("https://static.bshare.cn/cm.html")) {
            
            let webDetailsVC = WebDetailsViewController.init(urlString: urlString)
            self.navigationController?.pushViewController(webDetailsVC, animated: true)
            
            decisionHandler(.cancel)
            return
        }
        
        if (urlString?.contains("m.kameng98.com/mobile/details/i"))! {
            
            let webVC = WebViewController.init(urlString: urlString, title: nil)
            webVC.isSpecial = true
            self.navigationController?.pushViewController(webVC, animated: true)
            decisionHandler(.cancel)
            return
        }
        
        decisionHandler(.allow)
        
    }
    
    //MARK: 加载新网页
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        if navigationAction.targetFrame != nil {
            
            if !(navigationAction.targetFrame?.isMainFrame)! {
                webView.evaluateJavaScript("var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}", completionHandler: nil)
            }
        }
        
        
        
        decisionHandler(.allow)
    }
    
    
}
